<template>
  <div class="quiz-page">
    <van-nav-bar title="刷题练习" left-arrow @click-left="onClickLeft" />

    <!-- 进度条 -->
    <div class="progress-section">
      <div class="progress-info">
        <span class="progress-text">第 {{ currentQuestionIndex + 1 }} 题 / 共 {{ questions.length }} 题</span>
        <span class="question-type">{{ currentQuestion.type === 'single' ? '单选题' : '多选题' }}</span>
      </div>
      <van-progress
        :percentage="progressPercentage"
        stroke-width="1.07vw"
        color="#1989fa"
        track-color="#f5f7fa"
      />
    </div>

    <div class="quiz-content">
      <div class="question-card">
        <div class="question-stem">
          {{ currentQuestion.stem }}
        </div>

        <!-- 单选题选项 -->
        <div v-if="currentQuestion.type === 'single'" class="options-container">
          <div
            v-for="(option, index) in currentQuestion.options"
            :key="index"
            class="option-item"
            :class="{
              'selected': selectedOption === option.label,
              'correct': showAnswer && currentQuestion.answer.includes(option.label),
              'wrong': showAnswer && selectedOption === option.label && !currentQuestion.answer.includes(option.label)
            }"
            @click="selectOption(option.label)"
          >
            <div class="option-label">{{ option.label }}</div>
            <div class="option-text">{{ option.text }}</div>
            <div class="option-indicator">
              <van-icon v-if="showAnswer && currentQuestion.answer.includes(option.label)" name="success" />
              <van-icon v-else-if="showAnswer && selectedOption === option.label && !currentQuestion.answer.includes(option.label)" name="cross" />
            </div>
          </div>
        </div>

        <!-- 多选题选项 -->
        <div v-else class="options-container">
          <div
            v-for="(option, index) in currentQuestion.options"
            :key="index"
            class="option-item"
            :class="{
              'selected': selectedOptions.includes(option.label),
              'correct': showAnswer && currentQuestion.answer.includes(option.label),
              'wrong': showAnswer && selectedOptions.includes(option.label) && !currentQuestion.answer.includes(option.label)
            }"
            @click="toggleCheckbox(option.label)"
          >
            <div class="option-label">{{ option.label }}</div>
            <div class="option-text">{{ option.text }}</div>
            <div class="option-indicator">
              <van-icon v-if="showAnswer && currentQuestion.answer.includes(option.label)" name="success" />
              <van-icon v-else-if="showAnswer && selectedOptions.includes(option.label) && !currentQuestion.answer.includes(option.label)" name="cross" />
              <van-checkbox v-else :model-value="selectedOptions.includes(option.label)" />
            </div>
          </div>
        </div>

        <!-- 答案解析 -->
        <div v-if="showAnswer" class="answer-section">
          <div class="answer-header">
            <van-icon name="info-o" />
            <span>答案解析</span>
          </div>
          <div class="correct-answer">
            <strong>正确答案：</strong>{{ currentQuestion.answer.join(', ') }}
          </div>
          <div class="explanation">
            <strong>解析：</strong>{{ currentQuestion.explanation }}
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作区 -->
    <div class="quiz-footer">
      <div class="footer-actions">
        <!-- 未提交答案时显示提交按钮 -->
        <van-button
          v-if="!showAnswer"
          type="primary"
          size="large"
          round
          block
          :disabled="!hasSelectedAnswer"
          @click="submitAnswer"
          class="submit-btn"
        >
          提交答案
        </van-button>

        <!-- 已提交答案时显示导航按钮 -->
        <div v-else class="nav-buttons">
          <van-button
            type="default"
            size="large"
            round
            :disabled="currentQuestionIndex === 0"
            @click="prevQuestion"
            class="nav-btn prev-btn"
          >
            上一题
          </van-button>
          <van-button
            type="primary"
            size="large"
            round
            @click="nextQuestion"
            class="nav-btn next-btn"
          >
            {{ currentQuestionIndex === questions.length - 1 ? '完成练习' : '下一题' }}
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="QuizPage">
    import { ref, computed } from 'vue';
    import { useRouter } from 'vue-router';
    import { showToast } from 'vant';

    const router = useRouter();

    const questions = ref([
      {
        id: 1,
        type: 'single',
        stem: '以下哪个不是JavaScript的原始数据类型？',
        options: [
          { label: 'A', text: 'String' },
          { label: 'B', text: 'Number' },
          { label: 'C', text: 'Object' },
          { label: 'D', text: 'Boolean' },
        ],
        answer: ['C'],
        explanation: 'JavaScript的原始数据类型包括String、Number、Boolean、Null、Undefined、Symbol和BigInt。Object是引用数据类型。',
      },
      {
        id: 2,
        type: 'multiple',
        stem: '以下哪些是Vue 3的生命周期钩子函数？',
        options: [
          { label: 'A', text: 'created' },
          { label: 'B', text: 'mounted' },
          { label: 'C', text: 'beforeDestroy' },
          { label: 'D', text: 'onMounted' },
        ],
        answer: ['B', 'D'],
        explanation: 'Vue 3组合式API中，常用的生命周期钩子包括onMounted、onUpdated、onUnmounted等。created和beforeDestroy是Vue 2的选项式API钩子，在Vue 3中对应setup函数和onUnmounted。',
      },
      {
        id: 3,
        type: 'single',
        stem: 'HTML中用于定义页面标题的标签是？',
        options: [
          { label: 'A', text: '<head>' },
          { label: 'B', text: '<title>' },
          { label: 'C', text: '<body>' },
          { label: 'D', text: '<meta>' },
        ],
        answer: ['B'],
        explanation: '<title>标签用于定义HTML文档的标题，显示在浏览器标题栏或标签页上。',
      },
    ]);

    const currentQuestionIndex = ref(0);
    const selectedOption = ref('');
    const selectedOptions = ref([]);
    const showAnswer = ref(false);

    const currentQuestion = computed(() => questions.value[currentQuestionIndex.value]);

    const progressPercentage = computed(() => {
      return Math.round(((currentQuestionIndex.value + 1) / questions.value.length) * 100);
    });

    const hasSelectedAnswer = computed(() => {
      if (currentQuestion.value.type === 'single') {
        return selectedOption.value !== '';
      } else {
        return selectedOptions.value.length > 0;
      }
    });

    const onClickLeft = () => {
      router.back();
    };

    const selectOption = (option) => {
      if (!showAnswer.value) {
        selectedOption.value = option;
      }
    };

    const toggleCheckbox = (option) => {
      if (!showAnswer.value) {
        const index = selectedOptions.value.indexOf(option);
        if (index > -1) {
          selectedOptions.value.splice(index, 1);
        } else {
          selectedOptions.value.push(option);
        }
      }
    };

    const submitAnswer = () => {
      if (!hasSelectedAnswer.value) {
        showToast('请先选择答案');
        return;
      }
      showAnswer.value = true;

      // 检查答案是否正确
      let isCorrect = false;
      if (currentQuestion.value.type === 'single') {
        isCorrect = currentQuestion.value.answer.includes(selectedOption.value);
      } else {
        isCorrect = selectedOptions.value.length === currentQuestion.value.answer.length &&
                   selectedOptions.value.every(option => currentQuestion.value.answer.includes(option));
      }

      if (isCorrect) {
        showToast({ type: 'success', message: '回答正确！' });
      } else {
        showToast({ type: 'fail', message: '回答错误，请查看解析' });
      }
    };

    const nextQuestion = () => {
      if (currentQuestionIndex.value < questions.value.length - 1) {
        currentQuestionIndex.value++;
        resetAnswers();
      } else {
        showToast('练习完成！');
        router.push('/');
      }
    };

    const prevQuestion = () => {
      if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--;
        resetAnswers();
      }
    };

    const resetAnswers = () => {
      selectedOption.value = '';
      selectedOptions.value = [];
      showAnswer.value = false;
    };
</script>

<style scoped lang="scss">
  .quiz-page {
    min-height: 100vh;
    background-color: #f7f8fa;
    padding-bottom: 24vw;

    .van-nav-bar {
      background-color: #1989fa;

      :deep(.van-nav-bar__title) {
        color: white;
        font-weight: 600;
      }

      :deep(.van-icon) {
        color: white;
      }
    }

    .progress-section {
      background: white;
      padding: 4.26667vw;
      margin: 4.26667vw;
      border-radius: 2.13333vw;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      .progress-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 3.2vw;

        .progress-text {
          font-size: 3.73333vw;
          color: #323233;
          font-weight: 500;
        }

        .question-type {
          background-color: #ebf5ff;
          color: #1989fa;
          padding: 0.8vw 2.13333vw;
          border-radius: 2.13333vw;
          font-size: 3.2vw;
          font-weight: 500;
        }
      }

      :deep(.van-progress__portion) {
        background-color: #1989fa;
      }
    }

    .quiz-content {
      padding: 0 4.26667vw;

      .question-card {
        background: white;
        border-radius: 2.13333vw;
        padding: 4.26667vw;
        margin-bottom: 4.26667vw;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

        .question-stem {
          font-size: 4.26667vw;
          font-weight: bold;
          color: #323233;
          line-height: 1.5;
          margin-bottom: 4.26667vw;
        }

        .options-container {
          .option-item {
            display: flex;
            align-items: center;
            padding: 3.2vw 4.26667vw;
            margin-bottom: 3.2vw;
            border-radius: 2.13333vw;
            border: 1px solid #ebedf0;
            background: #ffffff;
            cursor: pointer;
            transition: all 0.3s ease;

            &:last-child {
              margin-bottom: 0;
            }

            &.selected {
              border-color: #1989fa;
              background: #ebf5ff;
            }

            &.correct {
              border-color: #07c160;
              background: #ecf9f2;
              color: #07c160;
            }

            &.wrong {
              border-color: #ee0a24;
              background: #fff1f0;
              color: #ee0a24;
            }

            .option-label {
              width: 7.46667vw;
              height: 7.46667vw;
              border-radius: 50%;
              background: #969799;
              color: white;
              display: flex;
              align-items: center;
              justify-content: center;
              font-weight: bold;
              font-size: 3.73333vw;
              margin-right: 3.2vw;
              flex-shrink: 0;
            }

            .option-text {
              flex: 1;
              font-size: 3.73333vw;
              line-height: 1.5;
              color: #323233;
            }

            .option-indicator {
              margin-left: 2.67vw;

              .van-icon {
                font-size: 4.8vw;
              }
            }

            &.selected .option-label {
              background: #1989fa;
            }

            &.correct .option-label {
              background: #07c160;
            }

            &.wrong .option-label {
              background: #ee0a24;
            }
          }
        }

        .answer-section {
          margin-top: 5.33333vw;
          padding: 4.26667vw;
          background-color: #ecf9f2;
          border-radius: 2.13333vw;
          border: 1px solid #d0f0e0;

          .answer-header {
            display: flex;
            align-items: center;
            margin-bottom: 3.2vw;
            font-size: 3.73333vw;
            font-weight: bold;
            color: #07c160;

            .van-icon {
              margin-right: 2.13333vw;
              font-size: 4.26667vw;
            }
          }

          .correct-answer,
          .explanation {
            margin-bottom: 2.13333vw;
            font-size: 3.73333vw;
            line-height: 1.5;
            color: #323233;

            &:last-child {
              margin-bottom: 0;
            }

            strong {
              color: #07c160;
              font-weight: bold;
            }
          }
        }
      }
    }

    .quiz-footer {
      position: fixed;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 100%;
      max-width: 750px;
      background: white;
      padding: 4.26667vw;
      box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
      border-top: 1px solid #ebedf0;
      z-index: 1000;

      .footer-actions {
        width: 100%;

        .submit-btn {
          width: 100%;
        }

        .nav-buttons {
          display: flex;
          gap: 2.66667vw;
          width: 100%;

          .nav-btn {
            flex: 1;
          }
        }

        .van-button {
          height: 11.73333vw !important;
          font-size: 4.26667vw !important;
          font-weight: 500 !important;
          border-radius: 5.86667vw !important;
        }

        .submit-btn {
          :deep(.van-button) {
            background-color: #1989fa !important;
            border-color: #1989fa !important;
            color: white !important;
            font-weight: 600 !important;
          }
        }

        .prev-btn {
          :deep(.van-button) {
            background: #f7f8fa !important;
            color: #646566 !important;
            border: 1px solid #ebedf0 !important;
          }
        }

        .next-btn {
          :deep(.van-button) {
            background-color: #1989fa !important;
            border-color: #1989fa !important;
            color: white !important;
          }
        }

        :deep(.van-button--disabled) {
          background: #f7f8fa !important;
          color: #c8c9cc !important;
          border-color: #ebedf0 !important;
        }
      }
    }
  }
</style>
